import {WebofficeProxyPlugin} from './WebofficeProxyPlugin'
import {invokeFunction} from "./function/CommonUtils";
import {MessageData, ProxyOpts} from "./types/Types";
let proxyServer:WebofficeProxyPlugin=new WebofficeProxyPlugin();
window.addEventListener("message", messageHandler, false);
function messageHandler(event:MessageEvent) {
    if(event.origin===location.origin)
        return;
    let options:ProxyOpts=event.data;
    let sourceWindow:Window=<Window>event.source;
    (<JQuery.Promise<any,any,any>>invokeFunction(options.method,proxyServer,options.args)).then(result=>{
        callback(sourceWindow,event.origin,options.success,result);
    },error=>{
        callback(sourceWindow,event.origin,options.fail,error);
    });
}
function callback(sourceWindow: Window, origin:string,callback:string|undefined,result: any) {
    if(callback===undefined)
        return;
    let resultData:MessageData={completeCb:<string>callback,result:JSON.parse(JSON.stringify(result))};//先把result转成json字符串然后再转成对象，过滤掉原result里面的函数
    sourceWindow.postMessage(resultData,origin);
}

function ready() {
    let readyMessage:MessageData={ready:true,completeCb:"",result:{}};
    window.parent.postMessage(readyMessage,"*");
}
$(function () {
    ready();
})
